package com.hospital.insurancepeople.client;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hospital.api.RemoteEndesctryptionService;
import com.hospital.common.core.module.entity.NFC.NFCResponse;
import com.hospital.common.core.result.SuccessTip;
import com.hospital.common.core.result.Tip;
import com.hospital.common.core.tioclient.LoginReqBody;
import com.hospital.insurancepeople.async.WxPayFunc;
import com.hospital.insurancepeople.handler.InvocationFactory;
import com.hospital.insurancepeople.handler.MessageInfo;
import com.hospital.insurancepeople.module.service.InsuranceLogsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.client.RestTemplate;
import org.tio.core.ChannelContext;
import org.tio.core.intf.Packet;
import org.tio.http.common.HttpResponse;
import org.tio.websocket.client.WsClientAioHander;
import org.tio.websocket.common.Opcode;
import org.tio.websocket.common.WsResponse;


/**
 * @author Administrator
 */
@Slf4j
public class WebsocketClientHandler extends WsClientAioHander {

    private WxPayFunc wxPayFunc;

    private InsuranceLogsService insuranceLogsService;

    private RemoteEndesctryptionService remoteEndesctryptionService;

    private RestTemplate restTemplate;


    public WebsocketClientHandler(WxPayFunc wxPayFunc, InsuranceLogsService insuranceLogsService, RemoteEndesctryptionService remoteEndesctryptionService,RestTemplate restTemplate) {
        this.remoteEndesctryptionService = remoteEndesctryptionService;
        this.wxPayFunc = wxPayFunc;
        this.insuranceLogsService = insuranceLogsService;
        this.restTemplate = restTemplate;
    }

    @Override
    public Packet heartbeatPacket(ChannelContext ctx) {
        LoginReqBody loginReqBody = new LoginReqBody();
        WsResponse wsResponse = WsResponse.fromText(JSON.toJSONString(loginReqBody), "utf-8");
        wsResponse.setWsEof(true);
        return wsResponse;
    }

    @Override
    public void handler(Packet packet, ChannelContext ctx) throws Exception {
//        super.handler(packet, ctx);
//        if (packet instanceof HttpResponse) {
//        } else {
//            WsResponse wsRequest = (WsResponse) packet;
//            if (wsRequest.getWsOpcode() == Opcode.TEXT) {
//                String value = new String(wsRequest.getBody(), "utf-8");
//                JSONObject jsonObject = JSON.parseObject(value);
//                JSONArray data = jsonObject.getJSONArray("data");
//                String tableName = jsonObject.getString("tableName");
//                String action = jsonObject.getString("action");
//                if (!action.equals("DELETE")) {
//                    for (Object jsonObject1 : data) {
//                        String uploadDate = JSON.parseObject(jsonObject1.toString()).getString("UPLOAD_DATE");
//                        String serialNo = JSON.parseObject(jsonObject1.toString()).getString("SERIAL_NO");
//                        //通过配置地址查看是否转发
//                        String url = insuranceLogsService.selectUrl(serialNo
//                                + "_URL");
//                        if (!Objects.isNull(url)) {
//                            //因表中无主键，因此根据查询条件查出几条就推送
//                            QueryWrapper<InsuranceLogs> queryWrapper = new QueryWrapper<>();
//                            queryWrapper.apply(" SERIAL_NO = {0} " +
//                                    "and UPLOAD_DATE =to_date({1},'yyyy-mm-dd hh24:mi:ss')", serialNo, uploadDate);
//                            List<InsuranceLogs> insuranceLogsList = insuranceLogsService.list(queryWrapper);
//                            if (!Objects.isNull(insuranceLogsList)) {
//                                for (InsuranceLogs insuranceLogs : insuranceLogsList) {
//                                    NFCResponse nfcResponse = new NFCResponse();
//                                    nfcResponse.setEncData("");
//                                    nfcResponse.setSignType("SM3");
//                                    nfcResponse.setAppSecret("1FM99V9JM00N9A23A8C000003F4B7C32");
//                                    nfcResponse.setAppId("1G00VOLSP0143F60C80A00005F9F40EF");
//                                    String insuranceJson = insuranceLogs.getInsuranceJson();
//                                    JSONObject jsonObject2 = JSON.parseObject(insuranceJson);
//                                    JSONObject input = jsonObject2.getJSONObject("input");
//                                    JSONArray jsonArray = input.getJSONArray("feedetail");
//                                    nfcResponse.setData(input.toJSONString());
//                                    NFCResponse enc = JSON.parseObject(remoteEndesctryptionService.getEnc(nfcResponse), NFCResponse.class);
//                                    enc.setUrl(url);
//                                    wxPayFunc.wxPay(enc);
//                                }
//                            }
//                        }
//
//                    }
//                }
//            }
//
//        }
//    }
        if (packet instanceof HttpResponse) {
        } else {
            WsResponse wsRequest = (WsResponse) packet;
            if (wsRequest.getWsOpcode() == Opcode.TEXT) {
                String value = new String(wsRequest.getBody(), "utf-8");
                JSONObject jsonObject = JSON.parseObject(value);
                JSONArray data = jsonObject.getJSONArray("data");
                String tableName = jsonObject.getString("tableName");
                String action = jsonObject.getString("action");
                if (!action.toUpperCase().equals("D") && !action.equals("DELETE")) {
                    for (Object jsonObject1 : data) {
                        JSONObject jsonObject4 = JSON.parseObject(jsonObject1.toString());
                        Tip tip = new SuccessTip(jsonObject4);
                        tip.setData(jsonObject4);
                        MessageInfo tableImp = InvocationFactory.getTableImp(tableName);
                        if (tableImp != null) {
                            NFCResponse hisInfo = tableImp.getHisInfo(tip, tableName, action);
                        }
                    }
                }
            }
        }
    }
}
